package com.example.elm.HomeAndSearch

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.Public.AddressActivity
import com.example.elm.Public.MyApplication
import com.example.elm.Public.StoreInfo
import com.example.elm.R
import com.example.elm.databinding.HomeMainBinding
import com.example.elm.StoreAndGoods.StoreActivity
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import kotlin.concurrent.thread

class HomeMainFragment:Fragment() {
    private val storeList = ArrayList<StoreInfo>()
    private val server_ip = MyApplication.serverIp // 服务器地址，这是手机热点的
    private lateinit var binding: HomeMainBinding
    private lateinit var  startForResult: ActivityResultLauncher<Intent>
    // onCreateView 负责创建视图
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 第一次从数据库读取数据，更新UI
        ReadHomeStoreByXml()
        // 使用 View Binding 绑定布局
        binding = HomeMainBinding.inflate(inflater, container, false)

        // 注册ActivityResultLauncher,用来接收从AddressActivity返回的结果
        startForResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            Log.d("ActivityResult", "Received result with code: ${result.resultCode}")
            if (result.resultCode == Activity.RESULT_OK) {
                //接收从AddressActivity返回的结果
                val updatedAddressData = result.data?.getStringExtra("address_data")
                Log.d("ActivityResult", "Returned Address: $updatedAddressData") // 检查返回值
                updatedAddressData?.let {
                    binding.tvAddress.text = it
                }
            }
        }

        // 返回绑定视图的根视图
        return binding.root
    }
    // onViewCreated 负责视图相关的数据初始化和操作
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 数据未能加载出来，点击按钮重新读取数据库
        binding.btnReload.setOnClickListener {
            ReadHomeStoreByXml()
        }
        // 布局管理器
        val layoutManager = LinearLayoutManager(requireContext())
        binding.homeRecyclerView.layoutManager = layoutManager
        val adapter = StoreAdapter(requireContext(),storeList)
        binding.homeRecyclerView.adapter = adapter
        binding.homeRecyclerView.addItemDecoration(SpaceItemDecoration(15))// 设置recyclerView子项的底部间距,10px

        // 设置搜索框点击事件，启动 SearchActivity 并传递 searchData 对象
        binding.btnSearch.setOnClickListener {
            val searchData = binding.etSearch.text.toString()
            val intent = Intent(activity, SearchActivity::class.java)
            intent.putExtra("search_data", searchData)
            startActivity(intent)
        }
        // 点击地址，跳转地址界面
        binding.Address.setOnClickListener {
            val intent = Intent(activity, AddressActivity::class.java)
            startForResult.launch(intent)
        }


        val headerView = layoutInflater.inflate(R.layout.home_header, null)
        val chipGroup = headerView.findViewById<ChipGroup>(R.id.chipGroup)
        chipGroup.setOnCheckedChangeListener{ group, checkedID ->
            if (checkedID != -1) {
                val selectedChip = group.findViewById<Chip>(checkedID)
                val selectedText = selectedChip.text
                Toast.makeText(requireContext(), "Selected: $selectedText", Toast.LENGTH_SHORT).show()
            }else {
                Log.e("MyFragment", "chipGroup is null! Check your layout ID.")
            }
        }
    }


    private class SpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            outRect.bottom = space  // 设置recyclerView子项的底部间距
        }
    }

    private class StoreAdapter(val context:Context ,
                               val StoreList: ArrayList<StoreInfo>)
        : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val VIEW_TYPE_HEADER = 0
        private val VIEW_TYPE_ITEM = 1

        override fun getItemViewType(position: Int): Int {
            return if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_HEADER) {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.home_header, parent, false
                )
                HeaderViewHolder(view)
            } else {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.home_store_elem, parent, false
                )
                StoreViewHolder(view).itemView.setOnClickListener {
                    val StoreName = view.findViewById<TextView>(R.id.tvName).text.toString()
                    val intent = Intent(context, StoreActivity::class.java)
                    intent.putExtra("store_data", StoreName)
                    context.startActivity(intent)
                }
                StoreViewHolder(view)
            }
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (getItemViewType(position) == VIEW_TYPE_ITEM) {
                val storeInfo = StoreList[position - 1] // 减去 header 占用的位置
                (holder as StoreViewHolder).bind(storeInfo)
            }
            // Header 不需要额外绑定逻辑，通常用于静态布局
        }

        override fun getItemCount(): Int {
            return StoreList.size + 1 // 多了一个 Header View
        }

        // Header ViewHolder
        class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

        // Store ViewHolder
        class StoreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val image: ImageView = itemView.findViewById(R.id.imageView)
            val name: TextView = itemView.findViewById(R.id.tvName)
            val delivertTime: TextView = itemView.findViewById(R.id.tvDeliveryTime)
            val distance: TextView = itemView.findViewById(R.id.tvDistance)
            val rating: TextView = itemView.findViewById(R.id.tvRating)
            val sales: TextView = itemView.findViewById(R.id.tvSales)
            val minPrice: TextView = itemView.findViewById(R.id.tvMinPrice)
            val deliveryCost: TextView = itemView.findViewById(R.id.tvDeliveryCost)
            val recommend: TextView = itemView.findViewById(R.id.tvRecommend)
            val campusSend: TextView = itemView.findViewById(R.id.tvCampusSend)

            fun bind(storeInfo: StoreInfo) {
                val imageResId = itemView.context.resources.getIdentifier(
                    storeInfo.image, "drawable", itemView.context.packageName
                )
                if (imageResId != 0) {
                    image.setImageResource(imageResId)
                } else {
                    image.setImageResource(R.drawable.cqxm)
                }
                name.text = storeInfo.name
                delivertTime.text = storeInfo.deliveryTime
                distance.text = storeInfo.distance
                rating.text = "${storeInfo.rating}分"
                sales.text = "月售${storeInfo.sales}+"
                minPrice.text = "起送￥${storeInfo.minPrice}"
                deliveryCost.text = storeInfo.deliveryCost
                recommend.text = storeInfo.recommend
                campusSend.text = if (storeInfo.campusSend > 0) "校园送" else ""
            }
        }
    }


    // 通过xml读取
    fun ReadHomeStoreByXml(){
        val homeStore_all = "http://$server_ip:8080/HomeAndSearch/get_all_HomeStore_xml.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(homeStore_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                // 确保在主线程更新 UI
                requireActivity().runOnUiThread {
                    if (!responseData.isNullOrEmpty()) {
                        binding.homeRecyclerView.visibility = View.VISIBLE
                        binding.linearLayoutSearch.visibility = View.VISIBLE
                        binding.bengkui.visibility = View.GONE
                        parseXml(responseData.trim()) // 解析返回的数据
                    } else {
                        showReloadButton("没有数据")
                    }
                }
            }
            catch (e: Exception){
                e.printStackTrace()
                requireActivity().runOnUiThread {
                    showReloadButton("加载失败，请检查网络")
                }
            }
        }
    }

    // 解析xml
    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            storeList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var idStr = ""
            var image = ""
            var name = ""
            var deliveryTime = ""
            var distance = ""
            var ratingStr = ""
            var salesStr = ""
            var minPriceStr = ""
            var deliveryCost = ""
            var recommend = ""
            var campusSendStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "id" -> idStr = xmlPullPaser.nextText()
                            "image" -> image = xmlPullPaser.nextText()
                            "name" -> name = xmlPullPaser.nextText()
                            "deliveryTime" -> deliveryTime = xmlPullPaser.nextText()
                            "distance" -> distance  = xmlPullPaser.nextText()
                            "rating" -> ratingStr = xmlPullPaser.nextText()
                            "sales" -> salesStr = xmlPullPaser.nextText()
                            "minPrice" -> minPriceStr = xmlPullPaser.nextText()
                            "deliveryCost" -> deliveryCost = xmlPullPaser.nextText()
                            "recommend" -> recommend = xmlPullPaser.nextText()
                            "campusSend" -> campusSendStr = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Store" == nodeName) {
                            storeList.add(
                                StoreInfo(
                                    idStr.toIntOrNull() ?: 0,
                                    image,
                                    name,
                                    deliveryTime,
                                    distance,
                                    ratingStr.toDoubleOrNull() ?: 0.0,
                                    salesStr.toIntOrNull() ?: 0,
                                    minPriceStr.toIntOrNull() ?: 0,
                                    deliveryCost,
                                    recommend,
                                    campusSendStr.toIntOrNull() ?: 0
                                )
                            )
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            if (isAdded) {
                requireActivity().runOnUiThread{
                    binding.homeRecyclerView.adapter?.notifyDataSetChanged()
                }
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }

    // 显示重新加载按钮的方法
    private fun showReloadButton(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
        binding.homeRecyclerView.visibility = View.GONE // 隐藏RecyclerView
        binding.linearLayoutSearch.visibility = View.GONE
        binding.bengkui.visibility = View.VISIBLE // 显示重新加载按钮
    }

}